import { config } from '../config.js'
import alert from './alert.js'

export class HTTP {
  request({ url, method = "GET", data = {} }) { // http请求
    let userInfo = wx.getStorageSync('userInfo')
    if(!userInfo) {
      return this._login().then(()=>{
        return this._request({ url, method , data })
      })
    } else {
      return this._request({ url, method , data })
    }
  }

  _request({ url, method, data = {} }) {
    wx.showNavigationBarLoading()
    return new Promise((resolve, reject) => {
      wx.request({
        url: config.httpUrl + url,
        method,
        data,
        header: this._setHttpHerder(),
        success: res => {
          wx.hideNavigationBarLoading() // 隐藏导航条加载动画
          if (res.statusCode === 200 || res.statusCode === 201) {
            resolve(res.data)
          } else if (res.statusCode === 404) {
            reject(res.data.message ? res.data.message : '请求地址不存在');
          } else if (res.statusCode === 401) {
            alert.alert('登录超时').then(()=>{
              console.log('登录超时')
              this._login().then(()=> {
                wx.switchTab({
                  url: '/pages/tabpage/index'
                })
              })
            })
          }else {
            reject(res.data.message)
          }
        },
        fail: err => {
          reject(err)
        }
      })
    })
  }

  _login() {
    return new Promise((resolve, reject)=>{
      wx.login({
        success:(res)=>{
          if(res.code) {
            wx.request({
              url: config.httpUrl + 'wxapp/openid',
              data: { code: res.code },
              method: 'GET', 
              success:(session)=>{
                wx.setStorageSync('userInfo', session.data);
                resolve(session.data);
              }
            })
          }
        },
        fail:()=> {
          reject()
        }
      })
    })
  }

  _setHttpHerder(){ // 设置请求头部信息
    let userInfo = wx.getStorageSync('userInfo')
    let header = {
      'content-type': 'application/json'
    }
    if(userInfo) {
      header.Authorization = 'Bearer ' + userInfo.token;
      header.OpenId = userInfo.openid;
    }
    return header
  }

  _show_error(code) {
    wx.showToast({
      title: code || '抱歉，发生了一个错误',
      icon: "none"
    })
  }
}